<template>
  <a-menu
    :defaultOpenKeys="['1']"
    :defaultSelectedKeys="['0_2']"
    @menuItemClick="onClickMenuItem"
  >
    <template v-for="item in menuList">
      <template v-if="!item.children || item.children?.length == 0">
        <a-menu-item :key="item.id.toString()">
          <component v-if="item.icon" :is="item.icon"></component>
          {{ item.title }}
        </a-menu-item>
      </template>
      <template v-else>
        <a-sub-menu :key="item.id.toString()">
          <template #title>
            <span>
              <component v-if="item.icon" :is="item.icon"></component>
              {{ item.title }}
            </span>
          </template>
          <a-menu-item
            v-for="child in item.children"
            :key="child.id.toString()"
          >
            {{ child.title }}
          </a-menu-item>
        </a-sub-menu>
      </template>
    </template>
  </a-menu>
</template>

<script lang="ts">
import { PropType, defineComponent, computed } from "vue";
import { useRouter } from "vue-router";
import icons from "@/common/icons";
import type { Menu } from "@/types/menu";
export default defineComponent({
  components: {
    ...icons,
  },
  props: {
    menu: {
      type: Array as PropType<Menu[]>,
      default: () => [],
    },
  },
  setup(props) {
    const router = useRouter();
    const menuList = computed(() => {
      let list = props.menu.map((item) => {
        return {
          ...item,
          icon: item.icon ? item.icon : "IconCalendar",
        };
      });
      return list;
    });
    const onClickMenuItem = (key: any) => {
      let path = pathCallback(menuList.value, key);
      if (path) {
        router.push(path);
      }
    };
    //回调函数
    const pathCallback = (list: Menu[], key: any): any => {
      let path = null;
      for (let i = 0; i < list.length; i++) {
        const element = list[i];
        if (element.id == key) {
          path = element.path;
          break;
        } else {
          if (element.children && element.children.length > 0) {
            path = pathCallback(element.children, key);
          }
        }
      }
      return path;
    };

    return {
      menuList,
      onClickMenuItem,
    };
  },
});
</script>

<style scoped>
</style>